package com.hx.er.common.system;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.hx.er.bean.base.UserBean;

public class ErSessions {
	private static Map<String, HttpSession> sessionMap = new HashMap<String, HttpSession>();
	private static Map<Long, UserBean> userLoginMap = new HashMap<Long, UserBean>();

	/**
	 * @param sessionId
	 * @param session
	 */
	public synchronized static void add(String sessionId, HttpSession session) {
		sessionMap.put(sessionId, session);
	}

	public synchronized static void remove(String sessionId, Long userId) {
		sessionMap.remove(sessionId);
		if (userId != null) {
			userLoginMap.remove(userId);
		}
	}

	/**
	 * 在登录成功后调用！
	 * 
	 * @param sessionId
	 */
	public synchronized static void login(String sessionId) {
		HttpSession session = sessionMap.get(sessionId);
		UserBean userBean = (UserBean) session.getAttribute(Constants.SESSION_USER_INFO);
		userLoginMap.put(userBean.getUserId(), userBean);
	}

	/**
	 * 在登出成功前调用！
	 * 
	 * @param sessionId
	 */
	public synchronized static void logout(String sessionId) {
		HttpSession session = sessionMap.get(sessionId);
		if (session == null) {
			// session过期的情况
			return;
		}		
		UserBean userBean = (UserBean) session.getAttribute(Constants.SESSION_USER_INFO);
		if (userBean == null) {
			// 服务器重启，或者用户信息被从session中移除的其他情况
			return;
		}
		userLoginMap.remove(userBean.getUserId());
	}

	public static int getSessionCount() {
		return sessionMap.size();
	}

	public static int getUserLoginCount() {
		return userLoginMap.size();
	}

	public static Map<Long, UserBean> getUserLoginMap() {
		return userLoginMap;
	}
}
